package cn.edu.wzut;

import cn.edu.wzut.entity.StockData;
import cn.edu.wzut.repository.StockDataRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.ResourceAccessException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class StockDataService {

    @Autowired
    private StockDataRepository stockDataRepository;

    private static final long POLL_INTERVAL_MS = 100; // 每次请求后等待n秒
    private RestTemplate restTemplate;

    public StockDataService() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 连接超时，单位毫秒
        factory.setReadTimeout(5000); // 读取超时，单位毫秒
        this.restTemplate = new RestTemplate(factory);
    }

    public void startFetchingData() {
        List<String> dates = generateDateRange("2022-01-04", "2024-06-07");
        for (String date : dates) {
            System.out.println("Start fetching data for date: " + date);

            boolean success = fetchAndSaveStockData(date);

            if (success) {
                System.out.println("Successfully fetched and saved data for date: " + date);
            } else {
                System.out.println("No valid data for date: " + date);
            }

            try {
                Thread.sleep(POLL_INTERVAL_MS);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    private List<String> generateDateRange(String startDate, String endDate) {
        List<String> dates = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();

        try {
            start.setTime(sdf.parse(startDate));
            end.setTime(sdf.parse(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
            return dates;
        }

        while (!start.after(end)) {
            int dayOfWeek = start.get(Calendar.DAY_OF_WEEK);
            if (dayOfWeek != Calendar.SATURDAY && dayOfWeek != Calendar.SUNDAY) {
                dates.add(sdf.format(start.getTime()));
            }
            start.add(Calendar.DATE, 1);
        }

        return dates;
    }

    private boolean fetchAndSaveStockData(String date) {
        String code = "000001";
        String url = "http://localhost:9090/stock?code=" + code + "&date=" + date; // 构建请求URL

        try {
            Map<String, Object> response = restTemplate.getForObject(url, Map.class);

            if (response != null) {
                System.out.println("Response received for date: " + date);
                Integer responseCode = (Integer) response.get("code");

                if (responseCode == 0) {
                    Map<String, String> data = (Map<String, String>) response.get("data");

                    if (data == null || data.isEmpty()) {
                        System.out.println("No data available for date: " + date);
                        return false;
                    }

                    StockData stockData = new StockData();
                    try {
                        stockData.setDate(new SimpleDateFormat("yyyy-MM-dd").parse(data.get("日期")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                        System.out.println("Error occurred while processing data for date: " + date);
                        return false;
                    }
                    stockData.setVolume(Long.parseLong(data.get("成交量")));
                    stockData.setLow(Double.parseDouble(data.get("最低")));
                    stockData.setOpen(Double.parseDouble(data.get("开盘")));
                    stockData.setTransactionAmount(Double.parseDouble(data.get("成交额")));
                    stockData.setChangeAmount(Double.parseDouble(data.get("涨跌额")));
                    stockData.setHigh(Double.parseDouble(data.get("最高")));
                    stockData.setAmplitude(Double.parseDouble(data.get("振幅")));
                    stockData.setChangePercentage(Double.parseDouble(data.get("涨跌幅")));
                    stockData.setClose(Double.parseDouble(data.get("收盘")));
                    stockData.setTurnoverRate(Double.parseDouble(data.get("换手率")));

                    stockDataRepository.save(stockData);
                    return true;
                } else {
                    System.out.println("Invalid response code for date: " + date + " - Code: " + responseCode);
                    return false;
                }
            } else {
                System.out.println("No response for date: " + date);
                return false;
            }
        } catch (ResourceAccessException e) {
            e.printStackTrace();
            System.out.println("Timeout occurred while fetching data for date: " + date);
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error occurred while fetching data for date: " + date);
            return false;
        }
    }
}